<template>
  <div class="home-page">
    <div class="filter-box">
      <div class="form-item">
        <div class="form-item-label">用户名：</div>
        <el-input v-model="filterName" placeholder="请输入用户名" :suffix-icon="Search" clearable />
      </div>
      <div class="btn-box">
        <!-- <el-button type="primary" @click="refreshData">刷新</el-button> -->
        <el-button type="primary" @click="addUserDialogVisible = true">新增用户</el-button>
      </div>
    </div>
    <div class="table-container">
      <el-table :data="tableData">
        <template v-for="item in columns" :key="item.prop">
          <el-table-column
            v-if="item.prop === 'operation'"
            :prop="item.prop"
            :label="item.label"
            :width="380"
            :style="{ display: 'flex' }"
          >
            <template #default="scope">
              <el-button
                size="small"
                type="primary"
                @click="
                  () => {
                    operationRow = scope.row
                    spendDialogVisible = true
                  }
                "
              >
                消费
              </el-button>
              <el-button
                size="small"
                type="success"
                @click="
                  () => {
                    operationRow = scope.row
                    topUpDialogVisible = true
                  }
                "
              >
                充值
              </el-button>
              <el-button
                size="small"
                type="warning"
                @click="
                  () => {
                    operationRow = scope.row
                    editUserInfoModalVisible = true
                  }
                "
              >
                修改
              </el-button>
              <el-button size="small" type="primary" @click="() => toBill(scope.row)">
                查看消费记录
              </el-button>
              <el-button size="small" type="danger" @click="() => deleteHandle(scope.row)">
                删除
              </el-button>
            </template>
          </el-table-column>
          <el-table-column v-else-if="item.prop === 'pets'" :prop="item.prop" :label="item.label">
            <template #default="scope">
              <div style="display: flex; flex-direction: column">
                <span v-for="(pet, index) in scope.row.pets" :key="index">{{
                  `${pet.name}-${pet.type}`
                }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column
            v-else-if="item.prop === 'petsAttention'"
            :prop="item.prop"
            :label="item.label"
          >
            <template #default="scope">
              <div style="display: flex; flex-direction: column">
                <span v-for="(pet, index) in scope.row.pets" :key="index">{{ pet.attention }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column v-else :prop="item.prop" :label="item.label" :width="item.width" />
        </template>
      </el-table>
    </div>
  </div>
  <AddUserFormModal v-if="addUserDialogVisible" v-model="addUserDialogVisible" />
  <SpendModal
    v-if="spendDialogVisible"
    v-model="spendDialogVisible"
    :operation-row="operationRow"
  />
  <TopUpModal
    v-if="topUpDialogVisible"
    v-model="topUpDialogVisible"
    :operation-row="operationRow"
  />
  <EditUserInfoModal
    v-if="editUserInfoModalVisible"
    v-model="editUserInfoModalVisible"
    :operation-row="operationRow"
  />
</template>

<script setup>
import { onMounted, ref, computed, toRaw } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useUsersStore, useBillStore } from '@/stores/index'
import AddUserFormModal from '@/components/AddUserFormModal.vue'
import SpendModal from '@/components/SpendModal.vue'
import TopUpModal from '@/components/TopUpModal.vue'
import EditUserInfoModal from '@/components/EditUserInfoModal.vue'
import { Search } from '@element-plus/icons-vue'
const userStore = useUsersStore()
const billStore = useBillStore()

const router = useRouter()

// 添加用户弹框显示状态
const addUserDialogVisible = ref(false)
// 消费弹框显示状态
const spendDialogVisible = ref(false)
// 充值弹框显示状态
const topUpDialogVisible = ref(false)
const editUserInfoModalVisible = ref(false)

// 当前操作行数据
const operationRow = ref({})

const columns = ref([
  {
    prop: 'name',
    label: '姓名',
    width: '120'
  },
  {
    prop: 'phone',
    label: '手机号',
    width: '120'
  },
  {
    prop: 'gender',
    label: '性别',
    width: '120'
  },
  {
    prop: 'pets',
    label: '宠物',
    width: '120'
  },
  {
    prop: 'petsAttention',
    label: '宠物备注信息'
  },
  {
    prop: 'amount',
    label: '余额',
    width: '150'
  },
  {
    prop: 'operation',
    label: '操作'
  }
])

const filterName = ref('')
const tableData = computed(() => {
  return userStore.userList.filter((item) => {
    if (filterName.value === '') return true
    else return item.name.includes(filterName.value)
  })
})

// 获取文件数据
const getFileData = (path) => {
  return new Promise((resolve, reject) => {
    window.nodeApi
      ?.readFile(path)
      .then((res) => {
        resolve(res)
      })
      .catch((err) => {
        console.log('err', err)
        reject(err)
      })
  })
}

const getUserList = () => {
  getFileData('/user.json').then(({ type, res }) => {
    if (type === 'success') {
      res = res === '' ? '[]' : res
      const userList = JSON.parse(res)
      userStore.setUserList(userList)
    }
    if (type === 'create') {
      ElMessage({
        message: '文件创建成功',
        type: 'success'
      })
    }
  })
}
const getBillList = () => {
  getFileData('/bill.json').then(({ type, res }) => {
    if (type === 'success') {
      const billList = res === '[]' ? [] : JSON.parse(`[${res.slice(0, -1)}]`)
      billStore.setBillList(billList)
    }
    if (type === 'create') {
      ElMessage({
        message: '文件创建成功',
        type: 'success'
      })
    }
  })
}

const refreshData = () => {
  getUserList()
  getBillList()
}

const toBill = (item) => {
  router.push({ path: '/bill', query: { name: item.name } })
}
const deleteUserInfo = (id) => {
  const userList = [...toRaw(userStore.userList)]
  const newList = userList.filter((item) => item.id !== id)
  window.nodeApi?.saveUserList(newList).then((res) => {
    ElMessage({
      message: '删除成功',
      type: 'success'
    })
    userStore.userList = newList
  })
}
const deleteHandle = (item) => {
  ElMessageBox.confirm('删除后的数据无法恢复，是否确认删除', '删除', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      deleteUserInfo(item.id)
    })
    .catch(() => {
      //
    })
}

// 获取文件数据并保存在pinia中
onMounted(() => {
  refreshData()
})
</script>

<style lang="scss" scoped>
.home-page {
  height: 100%;
  display: flex;
  flex-direction: column;
  box-sizing: border-box;
  .filter-box {
    margin-bottom: 24px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    .form-item {
      display: flex;
      align-items: center;
      &-label {
        margin-right: 10px;
        width: 100px;
      }
    }
  }
  .table-container {
    flex: 1;
    overflow: auto;
  }
}
</style>
